import NProgress from "nprogress";
import "nprogress/nprogress.css";
import type { Router } from "vue-router";

import { preferences } from "@/config/preference";
import { useAccessStore, useAuthStore, useOperateStore } from "@/store";
import { generateAccess } from "./access";

// console.log("=====: ", ["/", "/a"].join("/"), new URL(["/", "/a"].join("/")));
// console.log(["/b", "/a"].join("/"));

NProgress.configure({
  showSpinner: false,
});

function setCommonGuard(router: Router) {
  router.beforeEach((_to, _from) => {
    NProgress.start();
  });
  router.afterEach((_to, _from) => {
    NProgress.done();
  });
}

function setAuthGuard(router: Router) {
  const accessStore = useAccessStore();
  const authStore = useAuthStore();
  const operateStore = useOperateStore();
  router.beforeEach(async (to, from) => {
    // console.log("---to: ", to);
    // console.log("---from: ", from);
    if (to.meta.whitelist) return;
    // 逻辑待补充，检查token是否有效
    if (!accessStore.accessToken) {
      return {
        path: "/login",
        query: { redirect: to.fullPath },
      };
    }
    // 有token，验证token是否有效

    // 处理tabs,只处理BasicLayout children里的
    if (preferences.app.root === to.matched[0]?.name && to.path !== operateStore.tabRecords.at(-1))
      operateStore.clickMenu(to);

    if (accessStore.isAccessCheck) return;

    try {
      await Promise.all([authStore.fetchUserDetail(), generateAccess(router)]);
    } catch (e) {
      console.error("guard: fetch promise all: ", e);
    }
    accessStore.setAccessCheck(true);
    // 补充登录成功后跳转第一个页面相关逻辑
    if (preferences.app.login === from.path) {
      const resolved = router.resolve(to.path);
      if (resolved.matched.length < 2 && accessStore.accessRoute.length) {
        return accessStore.accessRoute[0];
      }
    }
    return to.fullPath;
    //   const res = await sleep(300);
  });
  // router.afterEach((to, from) => {

  // });
}

function createRouterGuard(router: Router) {
  setCommonGuard(router);
  setAuthGuard(router);
}

export { createRouterGuard };
